//
//  AddNotificationVC.m
//  NotificationMe
//
//  Created by max on 2018/12/16.
//  Copyright © 2018年 dayang. All rights reserved.
//

#import "AddNotificationVC.h"
#import "NMTableView.h"
#import "NMHomeTableViewCell.h"
#import "NMSelectionTableViewCell.h"
#import "NMSceneTableViewCell.h"
#import "NMStateItem.h"
#import "NMMapSeachViewController.h"
#import <UUKeyboardInputView.h>
@interface AddNotificationVC ()<UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate>
{
    NotificationType _type;
}

@property (nonatomic, strong) NMTableView *tableView;

@property (nonatomic, strong) NSArray *dataArray;

@property (nonatomic, strong) NSArray *titles;

@property (nonatomic, strong) NMItem *item;


@property (nonatomic, strong) NSArray *loctionArray;

@end

@implementation AddNotificationVC

- (instancetype)initWithNotificationType:(NotificationType)type {
    if (self = [super init]) {
        _type = type;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupViews];
    
    [self configureData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tableView reloadData];
}

- (void)notificationAdd {
    
    if (!(self.item.title.length && self.item.content.length)) {
        return;
    }
    
    NSMutableDictionary *content = @{}.mutableCopy;
    if (_type == NotificationTypeTime) {
        NMSceneTableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]];
        self.item.timeInterval = cell.picker.countDownDuration;
    
    }else if (_type == NotificationTypeCalendar) {
        NMSceneTableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]];
        NSCalendar *calendar = [NSCalendar currentCalendar];//当前用户的calendar
        NSDateComponents *comp = [calendar components:NSCalendarUnitYear | NSCalendarUnitMinute | NSCalendarUnitMonth | NSCalendarUnitHour | NSCalendarUnitDay fromDate:cell.picker.date];
        self.item.components = comp;
    }else {
        content[@"latitude"] = @([NMCLLocationManager shared].selectionCllocation.latitude);
        content[@"longitude"] = @([NMCLLocationManager shared].selectionCllocation.longitude);
        content[@"notifyOnEntry"] = @(self.item.locationItem.notifyOnEntry);
        content[@"notifyOnExit"] = @(self.item.locationItem.notifyOnExit);
    }
    
    content[@"title"] = self.item.title;
    content[@"body"] = self.item.content;
    content[@"sound"] = @(self.item.voice);
    content[@"repeat"] = @(self.item.repeat);
    content[@"radius"] = @(self.item.locationItem.radius);
    content[@"timeInterval"] = @(self.item.timeInterval);
    content[@"components"] = self.item.components;
    
    UNNotificationRequest *request = [NotificationFactory requestWithType:_type content:content];
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    //添加推送通知，等待通知即可！
    [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        
    }];

    [self.navigationController popViewControllerAnimated:true];
}

- (void)setupViews {
    
    if (_type == NotificationTypeTime) {
        self.title = @"Time Trigger";
    }else if (_type == NotificationTypeLocation) {
        self.title = @"Location Trigger";
    }else if (_type == NotificationTypeCalendar) {
        self.title = @"Calendar Trigger";
    }
    self.view.backgroundColor = [UIColor FFLightGray];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setBackgroundImage:[UIImage imageNamed:@"icon_back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backBarItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = backBarItem;
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(notificationAdd)];

    [self.view addSubview:self.tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view.mas_bottom);
    }];
}

- (void)configureData {
    
    self.item = [[NMItem alloc] init];
    self.item.title = @"title";
    self.item.content = @"content";
    
    self.item.locationItem = [[NMLocationItem alloc] init];
    self.item.locationItem.radius = 1000;
    
    self.titles = @[@"setting", @"scene"];
    
    NMStateItem *nameItem = [[NMStateItem alloc] init];
    nameItem.name = @"title";
    
    NMStateItem *contentItem = [[NMStateItem alloc] init];
    contentItem.name = @"content";
    
    
    NMActionItemModel *voice = [[NMActionItemModel alloc] init];
    voice.name = @"sound";
    
    
    NMActionItemModel *repeat = [[NMActionItemModel alloc] init];
    repeat.name = @"repeat";
    
    self.dataArray = @[nameItem,contentItem,voice,repeat];
    
    if (_type == NotificationTypeLocation) {
        [[NMCLLocationManager shared] requestAlwaysAuthorization];
        
        NMStateItem *radius = [[NMStateItem alloc] init];
        radius.name = @"radius(m)";
        
        NMActionItemModel *notifyOnEntry = [[NMActionItemModel alloc] init];
        notifyOnEntry.name = @"notifyOnEntry";
        
        NMActionItemModel *notifyOnExit = [[NMActionItemModel alloc] init];
        notifyOnExit.name = @"notifyOnExit";

        self.loctionArray = @[radius,notifyOnEntry,notifyOnExit];
    }
    
    [self.tableView reloadData];
}

- (void)backButtonClicked:(UIButton *)button {
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return self.titles[section];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (0 == section) {
        return self.dataArray.count;
    }
    switch (_type) {
        case NotificationTypeTime:return 1;
        case NotificationTypeLocation:return 4;
        case NotificationTypeCalendar:return 1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ((indexPath.section == 1 && indexPath.row == 3) ||
        (_type != NotificationTypeLocation && indexPath.section == 1 && indexPath.row == 0)) {
        return [NMSceneTableViewCell height];
    }else {
        return [NMHomeTableViewCell height];
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (0 == indexPath.section) {
        if (0 == indexPath.row || 1 == indexPath.row) {
            NMHomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kNMHomeTableViewCell forIndexPath:indexPath];
            NMStateItem *item = self.dataArray[indexPath.row];

            if (0 == indexPath.row) {
                item.title = self.item.title;
            }else {
                item.title = self.item.content;
            }
            
            [cell updateTitle:item.name subtitle:item.title];
            return cell;
        }else {
            NMSelectionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kNMSelectionTableViewCell forIndexPath:indexPath];
            NMActionItemModel *item = self.dataArray[indexPath.row];
            if (2 == indexPath.row) {
                item.enable = self.item.voice;
            }else {
                item.enable = self.item.repeat;
            }
            
            [cell updateTitle:item.name selected:item.enable];
            return cell;
        }
    }else {
        switch (_type) {
            case NotificationTypeTime: {
                NMSceneTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kNMSceneTableViewCell forIndexPath:indexPath];
                [cell setStyle:NMSceneStyleCountDownTimer];
                return cell;
            }
                
            case NotificationTypeLocation: {
                if (0 == indexPath.row) {
                    NMHomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kNMHomeTableViewCell forIndexPath:indexPath];
                    NMStateItem *item = self.loctionArray[indexPath.row];
                    item.title = [NSString stringWithFormat:@"%d",self.item.locationItem.radius];
                    [cell updateTitle:item.name subtitle:item.title];
                    return cell;
                }else if (1 == indexPath.row || 2 ==indexPath.row) {
                    NMSelectionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kNMSelectionTableViewCell forIndexPath:indexPath];
                    NMActionItemModel *item = self.loctionArray[indexPath.row];
                    if (1 == indexPath.row) {
                        item.enable = self.item.locationItem.notifyOnEntry;
                    }else {
                        item.enable = self.item.locationItem.notifyOnExit;
                    }
                    [cell updateTitle:item.name selected:item.enable];
                    return cell;
                }else {
                    NMSceneTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kNMSceneTableViewCell forIndexPath:indexPath];
                    [cell setStyle:NMSceneStyleMap];
                    return cell;
                }
            }
                
            case NotificationTypeCalendar: {
                NMSceneTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kNMSceneTableViewCell forIndexPath:indexPath];
                [cell setStyle:NMSceneStyleDateAndTime];
                return cell;
            }
        }
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (0 == indexPath.section) {
        if (0 == indexPath.row) {
            [UUKeyboardInputView showKeyboardConfige:^(UUInputConfiger * _Nonnull configer) {
                configer.backgroundColor = [[UIColor FFGray] colorWithAlphaComponent:0.3];
                configer.content = self.item.title;
            } block:^(NSString * _Nullable contentStr) {
                self.item.title = contentStr;
                [self.tableView reloadData];
            }];
        }else if (1 == indexPath.row) {
            [UUKeyboardInputView showKeyboardConfige:^(UUInputConfiger * _Nonnull configer) {
                configer.backgroundColor = [[UIColor FFGray] colorWithAlphaComponent:0.3];
                configer.content = self.item.content;
            } block:^(NSString * _Nullable contentStr) {
                self.item.content = contentStr;
                [self.tableView reloadData];
            }];
        }else if (2 == indexPath.row) {
            self.item.voice = !self.item.voice;
            [tableView reloadData];
        }else if (3 == indexPath.row) {
            self.item.repeat = !self.item.repeat;
            [tableView reloadData];
        }
    }else if (1 == indexPath.section && _type == NotificationTypeLocation) {
        if (0 == indexPath.row) {
            [UUKeyboardInputView showKeyboardConfige:^(UUInputConfiger * _Nonnull configer) {
                configer.keyboardType = UIKeyboardTypeNumberPad;
                configer.backgroundColor = [[UIColor FFGray] colorWithAlphaComponent:0.3];
                configer.content = [NSString stringWithFormat:@"%d",self.item.locationItem.radius];
            } block:^(NSString * _Nullable contentStr) {
                self.item.locationItem.radius = [contentStr intValue];
                [self.tableView reloadData];
            }];
        }else if (1 == indexPath.row) {
            self.item.locationItem.notifyOnEntry = !self.item.locationItem.notifyOnEntry;
            [tableView reloadData];
        }else if (2 == indexPath.row) {
            self.item.locationItem.notifyOnExit = !self.item.locationItem.notifyOnExit;
            [tableView reloadData];
        }else if (3 == indexPath.row) {
            NMMapSeachViewController *vc = [[NMMapSeachViewController alloc] init];
            [self.navigationController pushViewController:vc animated:true];
        }
    }
}

#pragma mark - Properties
- (NMTableView *)tableView {
    if (!_tableView) {
        _tableView = [[NMTableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.backgroundColor = [UIColor FFLightGray];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.dataSource = self;
        _tableView.delegate = self;
        [_tableView registerClass:[NMHomeTableViewCell class] forCellReuseIdentifier:kNMHomeTableViewCell];
        [_tableView registerClass:[NMSelectionTableViewCell class] forCellReuseIdentifier:kNMSelectionTableViewCell];
        [_tableView registerClass:[NMSceneTableViewCell class] forCellReuseIdentifier:kNMSceneTableViewCell];
    }
    return _tableView;
}


@end
